package wiz.client.activities;

import java.util.List;

import wiz.client.ClientFactory;
import wiz.client.activities.GameScoreView.SummaryTableCell;
import wiz.client.model.WizGameModel;
import wiz.client.model.WizGameRound;
import wiz.client.model.WizPlayer;
import wiz.client.model.WizPlayerRoundScore;

import com.google.gwt.user.client.ui.HasText;

public class GameScorePresenter {
	
	private GameScoreView fView;
	private ClientFactory fClientFactory;

	public GameScorePresenter(ClientFactory cf, GameScoreView view){
		fView = view;
		fClientFactory = cf;
	}
	
	public void displayGameState(WizGameModel loadGameState) {
		fView.clearTable();
		List<WizPlayer> wizPlayers = loadGameState.getWizPlayers();
		HasText[] createAndAddSummaryTableHeader = fView.createAndAddSummaryTableHeader(wizPlayers.size());
		for(int i = 0; i < wizPlayers.size(); i++){
			createAndAddSummaryTableHeader[i].setText(wizPlayers.get(i).getName());
		}
		
		int playerScores[] = new int[wizPlayers.size()];
		
		List<WizGameRound> gameRounds = loadGameState.getGameRounds();
		
		for (WizGameRound wizGameRound : gameRounds) {
			SummaryTableCell[] createAndAddSummaryTableRow = fView.createAndAddSummaryTableRow(wizPlayers.size());
			
			List<WizPlayerRoundScore> roundScores = wizGameRound.getRoundScores();
			
			for(int i = 0; i < wizPlayers.size(); i++){
				WizPlayerRoundScore playerScore = findRoundScoreForPlayer(wizPlayers.get(i),roundScores);
				
				createAndAddSummaryTableRow[i].getTricksBid().setText(playerScore.getTricksBid() + ""); //$NON-NLS-1$
				createAndAddSummaryTableRow[i].getTricksMade().setText(playerScore.getTricksMade() + ""); //$NON-NLS-1$
				
				int currentPlayerScore = playerScores[i];
				int newScore = fClientFactory.getWizGameDetails().calculateNewScore(currentPlayerScore, playerScore);
				playerScores[i] = newScore;
				createAndAddSummaryTableRow[i].getScore().setText("" + playerScores[i]); //$NON-NLS-1$
			}
		}
		
		if(gameRounds.size() > 6){
			HasText[] footer = fView.createAndAddSummaryTableHeader(wizPlayers.size());
			for(int i = 0; i < wizPlayers.size(); i++){
				footer[i].setText(wizPlayers.get(i).getName());
			}
		}
		
	}

	private WizPlayerRoundScore findRoundScoreForPlayer(WizPlayer wizPlayer, List<WizPlayerRoundScore> roundScores) {
		for (WizPlayerRoundScore roundScore : roundScores) {
			if(roundScore.getPlayer().getName().equals(wizPlayer.getName())){
				return roundScore;
			}
		}
		
		throw new IllegalArgumentException();
	}


}
